package br.com.duduso.conferencia_claro_desktop.dbf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Classe Utilitária Para Geração de Arquivos
 * no Formato DBF
 * @author duduso
 */
public class DBFUtils {

    /**
     * Gera Arquivo no Formato DBF, Considerando os Campos (Fields)
     * e as Linhas do DBF (List<Object> rows)
     * @param DBFField[] fields
     * @param List<Object> rows
     * @param String pathFile
     * @throws DBFException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void gerarArquivoDBF(DBFField[] fields, List<Object[]> rows, String pathFile)
            throws DBFException, FileNotFoundException, IOException{

            DBFWriter writer = new DBFWriter();
            writer.setFields(fields);

            for(Object[] row : rows){
                    writer.addRecord(row);
            }

            FileOutputStream fos = new FileOutputStream(new File(pathFile));
            writer.write(new FileOutputStream(pathFile));
            fos.close();

    }
    

    /**
     * Recupera um Array de Fields do DBF
     * @param DBFReader reader
     * @return DBFField[] fields
     * @throws DBFException
     */
    public static DBFField[] getFields(DBFReader reader) throws DBFException{

            int fieldCount = reader.getFieldCount();
            
            DBFField[] fields = new DBFField[fieldCount];

            for(int i = 0; i < fieldCount; i++){
                    if(i == 1){
                            DBFField field = reader.getField(i);
                            field.setFieldLength(43);
                            fields[i] = field;
                    }else if(i == 59){
                            DBFField field = reader.getField(i);
                            field.setFieldLength(8);
                            field.setDataType(DBFField.FIELD_TYPE_D);
                            fields[i] = field;
                    }else{
                            fields[i] = reader.getField(i);
                    }
            }

            return fields;

    }

    /**
     * Recupera uma Lista de Object[] (linhas) de Um Determinado DBF
     * @param DBFReader reader
     * @return List<Object[]> rows
     * @throws DBFException
     */
    public static List<Object[]> getRows(DBFReader reader) throws DBFException{
            
            List<Object[]> rows = new ArrayList<Object[]>();

            Object[] row;

            while((row = reader.nextRecord()) != null){
                    rows.add(row);
            }

            return rows;

    }

}
